package unrn.isiii.bean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import unrn.isiii.dao.TaskDao;
import unrn.isiii.model.Task;

@Component("taskHome")
public class TaskHome {

	private static final Logger logger = LoggerFactory
			.getLogger(TaskHome.class);

	private Task task = new Task();
	private List<Task> tasks;

	@Autowired
	private TaskDao taskDao;

	public String getMessage() {
		logger.debug("Returning message from task home bean");
		return "Hello from Spring";
	}

	public Task getTask() {
		return task;
	}

	public TaskDao getTaskDao() {
		return taskDao;
	}

	public void setTaskDao(TaskDao taskDao) {
		this.taskDao = taskDao;
	}

	public void setTask(Task task) {
		this.task = task;
	}

	public void setTasks(List<Task> tasks) {
		this.tasks = tasks;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void saveTask() {
		if (task.getId() == null)
			taskDao.create(task);
		else
			taskDao.update(task);
		task = new Task();
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Alta",
				"Operación realizada con éxito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void eliminar(Long id) {
		taskDao.delete(id);
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Borrar", "Operación realizada con éxito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	private void invalidateTasks() {
		tasks = null;
	}

	public List<Task> getTasks() {
		if (tasks == null) {
			tasks = taskDao.findAll();
		}
		return tasks;
	}
	
	public void seleccionarTarea(Task task)
	{
		setTask(task);
	}
}
